﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace CLFramework.MSSqlExport
{
    public static class XmlNodeExtension
    {
        public static string GetStringAttribute(this XmlNode node, string key, string defaultValue)
        {
            XmlAttributeCollection attributes = node.Attributes;
            if (attributes[key] != null
                && !string.IsNullOrEmpty(attributes[key].Value))
                return attributes[key].Value;
            return defaultValue;
        }

        public static int GetIntAttribute(this XmlNode node, string key, int defaultValue)
        {
            XmlAttributeCollection attributes = node.Attributes;
            int val = defaultValue;

            if (attributes[key] != null
                && !string.IsNullOrEmpty(attributes[key].Value))
            {
                int.TryParse(attributes[key].Value, out val);
            }
            return val;
        }

        public static float GetFloatAttribute(this XmlNode node, string key, float defaultValue)
        {
            XmlAttributeCollection attributes = node.Attributes;
            float val = defaultValue;

            if (attributes[key] != null
                && !string.IsNullOrEmpty(attributes[key].Value))
            {
                float.TryParse(attributes[key].Value, out val);
            }
            return val;
        }

        public static bool GetBoolAttribute(this XmlNode node, string key, bool defaultValue)
        {
            XmlAttributeCollection attributes = node.Attributes;
            bool val = defaultValue;

            if (attributes[key] != null
                && !string.IsNullOrEmpty(attributes[key].Value))
            {
                bool.TryParse(attributes[key].Value, out val);
            }
            return val;
        }

        public static T GetEnumAttribute<T>(this XmlNode node, string key, T defaultValue)
            where T : struct
        {
            string val = GetStringAttribute(node, key, defaultValue.ToString());
            T t = defaultValue;
            try
            {
                t = (T)Enum.Parse(typeof(T), val);
            }
            catch
            {
                t = defaultValue;
            }

            return t;
        }

        ////Support only .NET 4.0+
        //public static T GetEnumAttribute<T>(this XmlNode node, string key, T defaultValue)
        //    where T : struct
        //{
        //    string val = GetStringAttribute(node, key, defaultValue.ToString());
        //    T t = defaultValue;
        //    if (!Enum.TryParse<T>(val, out t))
        //        t = defaultValue;
        //    return t;
        //}
    }
}
